<template>
  <div class="background-container">
    <div class="container">
      <div style="margin: auto;justify-content: center;align-items: center;width: 1000px">
        <div style="height: 100%;">
          <el-carousel :interval="4000" type="card" height="230px">
            <el-carousel-item v-for="(medicine, index) in xiyaomedicines" :key="index">
              <div class="medicine-card1">
                <img
                  :src="medicine.imageUrl"
                  @click="navigateToDetails(medicine.id,medicine.skuId)"
                  alt="药品图片"
                  width="70px"
                  height="80px"
                  :class="{ 'image-hover-effect': isHovered }"
                  @mouseover="handleMouseOver"
                  @mouseout="handleMouseOut"
                />
                <div style="display: flex"><el-tag size="small">药名:</el-tag><h1 style="font-size: 13px;vertical-align: middle">{{ medicine.name }}</h1></div>
                <div class="textp" style="display: flex;"><el-tag size="small">分类:</el-tag><p title="别名" style="font-size: 12px;vertical-align: middle">{{medicine.category}}</p></div>
                <div style="margin-left: 10px; float: right;">
                  <el-link  @click="navigateToDetails(medicine.id,medicine.skuId)" :underline="false" style="font-size: 16px;border: none">查看详情<i class="el-icon-arrow-right"></i></el-link>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <div class="selectype" style="">
        <el-select v-model="skuType"  placeholder="分类查询" style="width: 120px" @change="handleSelectType">
          <el-option
            v-for="(item, index) in medicineTypeValue"
            :key="index"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </div>
        <div class="liu-form-inline" style="">
          <div >
            <el-form ref="dataEditForm" :inline="true" @keyup.enter.native="searchMedicine" :model="page" class="demo-form-inline" >
              <el-form-item label="">
                <el-autocomplete
                  class="autocomplete-border"
                  v-model="page.queryString"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="handleSelect"
                  ref="autocompleteRef"
                  style="width: 100%;margin: 0px;padding: 0px;"
                  id="1">
                  <template v-slot="{ item }">
                    <div>
                      <div class="val" @click="searchMedicine"><i class="el-icon-search" style="margin-right: 10px"></i>{{ item.value || item.alias }}</div>
                      <!--                  <div class="val"><i class="el-icon-search" style="margin-right: 10px"></i>{{ item.num }}</div>-->
                    </div>
                  </template>
                </el-autocomplete>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchMedicine">搜索</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="success" icon="el-icon-refresh" @click="clearValue">清空</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div v-if="showCard" class="results" id="searchResults">
          <error-index v-if="isNull"></error-index>
          <div class="html-body">
            <div class="content-page">
              <div v-for="item in medicineList" :key="item.id">
                <div class="item-container">
                  <div class="title">
                    <h3 v-if="item.skuId == 1" @click="navigateToDetailsInfoliu(item.id,item.skuId)">
                      <a>{{item.name}}</a>
                    </h3>
                    <h3 v-if="item.skuId == 2" @click="detailInfoTranditionlMedincine(item.id,item.skuId)">
                      <a>{{item.name}}</a>
                    </h3>
                    <h3 v-if="item.skuId == 3" @click="detailInfoTranditionlMedincine(item.id,item.skuId)">
                      <a>{{item.componentName}}</a>
                    </h3>
                  </div>
                  <div class="content">
                    <p v-if="item.skuId == 1"  @click="detailInfoTranditionlMedincine(item.id,item.skuId)">
                      <a v-if="lighlightFields(item.id) !== ''" v-html="lighlightFields(item.id)"></a>
                      <a v-else>{{item.category}}</a>
                      {{item.clinicalApplication}}
                    </p>
                    <p v-else-if="item.skuId == 2" @click="detailInfoTranditionlMedincine(item.id,item.skuId)">
                      <a v-if="lighlightFields(item.id) !== ''" v-html="lighlightFields(item.id)"></a>
                      <a v-else>{{item.adverseReaction}}</a>
                    </p>
                    <p v-else-if="item.skuId == 3" @click="detailInfoTranditionlMedincine(item.id,item.skuId)">
                      <a v-if="lighlightFields(item.id) !== ''" v-html="lighlightFields(item.id)"></a>
                      <a v-else>{{item.mainEffect}}</a>
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>
</template>

<script>
import { medicine, searchTcMedicineClient, TcMedicineClient } from '@/api/medicine'
import ErrorIndex from '@/views/error/ErrorIndex'
// import particlesConfig from '../particles/particles.json'
import { tcCategory } from '@/api/category'
import request from '@/api/request'
export default {
  components: {
    ErrorIndex
    // dataShow,
    // VideoPlayer
  },
  data () {
    return {
      showCard: false,
      dataInfo: [],
      isHovered: false,
      selectedValue: null,
      loading: false,
      skuType: '',
      image: '',
      medicineList: {},
      isNull: false,
      medicineTypeValue: [
        {
          value: '1',
          label: '中药材'
        },
        {
          value: '3',
          label: '中成药'
        },
        {
          value: '2',
          label: '西药'
        }
      ],
      // imageUrl: '',
      medicineInput: '',
      formData: {},
      searchResult: '',
      // medicines: [],
      medicines: [],
      xiyaomedicines: {},
      medicine2: [],
      list: {},
      categoryMedicineList: [],
      page: {
        total: 7,
        currentPage: 1,
        pageSize: 1,
        queryString: ''
      },
      positionPage: {
        total: 7,
        currentPage: 1,
        pageSize: 10,
        queryString: ''
      },
      highlight: [],
      positionPage2: {
        totalCount: 7,
        pageNo: 1,
        pageSize: 12
      },
      hardcodedSuggestions: [{ value: '土地', num: 7 }, { value: '行政', num: 4 }, { value: '案件', num: 3 }],
      keywords: ''
    }
  },
  beforeRouteLeave (to, from, next) {
    // 使用replaceState方法替换浏览器的历史记录，而不是推入新的历史记录
    window.history.replaceState({ key: 'value' }, '', window.location.href)
    next()
  },
  created () {
    // this.getData()
    this.searchMedicineList()
    this.categoryMedicine()
    // this.List()
    this.xiyaosearchMedicineList()
  },
  mounted () {
  },
  methods: {
    querySearch (queryString, cb) {
      const restaurants = this.hardcodedSuggestions
      const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      cb(results)
    },
    createFilter (queryString) {
      return (restaurant) => {
        // 在调用 toLowerCase 之前检查是否为 null
        return restaurant.value && restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    handleSelect (item) {
      // console.log(item)
    },
    navigateToDetails (id, skuId) {
      // alert(skuId)
      // this.$router.push({ name: 'details', query: { id } })
      const frontToken = localStorage.getItem('ordinaryUserToken')
      // alert(frontToken)
      const backToken = localStorage.getItem('token')
      // alert(backToken)
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')// 触发事件 进入详情页 需要先登录 后台登陆后在查看详情页面就不需要再次登录
      } else {
        // this.$router.push({ name: 'westernMedicineThemeDetails', params: { id: id } })
        // this.$router.push({ name: 'westernMedicineThemeDetails', params: { id: id } })
        if (skuId === '1') {
          this.$router.push({
            name: 'traditionalChineseMedicineDetails',
            params: {
              id: id
            }
          })
          return
        }
        if (skuId === '2') {
          this.$router.push({
            name: 'westernMedicineThemeDetails',
            params: {
              id: id
            }
          })
        }
      }
    },
    navigateToDetailsInfoliu (id, skuId) {
      // this.$router.push({ name: 'traditionalChineseMedicineDetails', params: { id: id } })
      if (skuId === '1') {
        // this.$router.push({ name: 'traditionalChineseMedicineDetails', params: { id: id } })
        // window.location.href = `http://localhost:5555/?#/traditionalChineseMedicineDetails/${id}.html`
        window.open(`/#/traditionalChineseMedicineDetails/${id}.html`, '_blank')
        return
      }
      if (skuId === '2') {
        // this.$router.push({ name: 'westernMedicineThemeDetails', params: { id: id } })
        window.open(`/#/westernMedicineThemeDetails/${id}.html`, '_blank')
        return
      }
      if (skuId === '3') {
        // this.$router.push({ name: 'proprietaryChineseMedicinesDeatils', params: { id: id } })
        window.open(`/#/proprietaryChineseMedicinesDeatils/${id}.html`, '_blank')
      }
    },
    detailInfoTranditionlMedincine (id, skuId) {
      // alert(id)
      if (skuId === '1') {
        // this.$router.push({ name: 'traditionalChineseMedicineDetails', params: { id: id } })
        window.open(`/#/traditionalChineseMedicineDetails/${id}.html`, '_blank')
        return
      }
      if (skuId === '2') {
        // this.$router.push({ name: 'westernMedicineThemeDetails', params: { id: id } })
        window.open(`/#/westernMedicineThemeDetails/${id}.html`, '_blank')
        return
      }
      if (skuId === '3') {
        // this.$router.push({ name: 'proprietaryChineseMedicinesDeatils', params: { id: id } })
        window.open(`/#/proprietaryChineseMedicinesDeatils/${id}.html`, '_blank')
      }
    },
    async searchMedicine () {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      if (this.page.queryString === '') {
        this.$message({
          message: '请输入药品名称',
          type: 'warning',
          center: true
        })
        return
      }
      if (this.page.queryString === '') {
        this.$message({
          message: '请输入药品名称',
          type: 'warning',
          center: true
        })
        return
      }
      const queryString = this.page.queryString
      const page = this.page.currentPage
      const size = this.page.pageSize
      try {
        await request.get(`/search/getInfo/clients/${page}/${size}?skuId=${this.skuType}&queryString=${queryString}`).then(resp => {
          if (resp.data.data.length === 0) {
            // alert(resp.data.data)
            this.isNull = true
            this.medicineList = {}
            this.showCard = true
            return
          }
          const data = resp.data
          this.medicine2 = data.data
          this.medicineList = data.data
          this.highlight = resp.data.highlight
          this.showCard = true
          this.isNull = false
          this.lighlightFields()
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    // 清空
    clearValue () {
      this.skuType = ''
      // this.searchMedicine()
      // this.showCard = false
      // this.page.queryString = ''
    },
    lighlightFields (id) {
      if (this.highlight !== null) {
        const highlight = this.highlight.find(item => item.id === id)
        if (highlight !== undefined && highlight.content !== undefined) {
          // alert(highlight.content)
          highlight.content.replace(/<em>/g, '<b>')
          return highlight.content
        } else {
          return ''
        }
      } else {
        return ''
      }
    },
    async searchMedicines () {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      if (this.page.queryString === '') {
        this.$message({
          message: '请输入药品名称',
          type: 'warning',
          center: true
        })
        return
      }
      const classData = {
        currentPage: this.page.currentPage,
        pageSize: this.page.pageSize,
        category: this.page.queryString
      }
      try {
        await searchTcMedicineClient(classData).then(resp => {
          // if (resp.data.data == null) {
          //   this.isNull = true
          //   return
          // }
          const data = resp.data
          this.medicine2 = data.rows
          // console.log(this.medicine2)
          this.showCard = true
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async xiyaosearchMedicineList () {
      const classData = {
        currentPage: this.positionPage.currentPage,
        pageSize: this.positionPage.pageSize,
        queryString: this.positionPage.queryString
      }
      try {
        await medicine(classData).then(resp => {
          const data = resp.data
          this.positionPage.total = data.total
          // this.medicine2 = data.rows
          this.xiyaomedicines = data.rows
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async searchMedicineList () {
      const classData = {
        currentPage: this.positionPage.currentPage,
        pageSize: this.positionPage.pageSize,
        queryString: this.positionPage.queryString
      }
      try {
        await TcMedicineClient(classData).then(resp => {
          const data = resp.data
          this.positionPage.total = data.total
          // this.medicine2 = data.rows
          this.medicines = data.rows
          this.hardcodedSuggestions = data.rows.map(item => ({ value: item.name, alias: item.alias }))
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async List () {
      try {
        const pageNo = this.positionPage2.pageNo
        const pageSize = this.positionPage2.pageSize
        // https://server.dayi.org.cn/api/cmedical/list2?pageNo=1&pageSize=10
        await this.$axiosApi.myAxios.get('/cmedical/list2?' + 'pageNo=' + pageNo + '&' + 'pageSize=' + pageSize).then(resp => {
          const data = resp.data
          this.dataInfo = resp
          this.positionPage2.totalCount = data.totalCount
          // this.medicine2 = data.rows
          this.list = data.list
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    westernMedicine () {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push('/westernMedicine.html')
    },
    tranditionalMedicineCategoryView () {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push('/tranditionalMedicineCategory.html')
    },
    // 获取分类
    categoryMedicine () {
      tcCategory().then(resp => {
        this.categoryMedicineList = resp.data.map(item => item.category)
        // alert(this.categoryMedicineList)
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    navigateToCategory (category) {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push({ name: 'cagetoryMedicine', params: { category } })
    },
    // initParticlesEffect () {
    //   window.particlesJS('particles-js', particlesConfig)
    // },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    },
    detile () {
      // console.log('详情')
      this.$router.push('/details')
    },
    // 客户端搜索
    handleSelectType (value) {
      this.skuType = value
      this.searchMedicine()
    },
    handleSizeChange (pageSize) {
      this.positionPage.pageSize = pageSize
      this.searchMedicineList()
    },
    handleCurrentChange (currentPage) {
      this.positionPage.currentPage = currentPage
      this.searchMedicineList()
    },
    currentPage3 () {},
    handleMouseOver () {
      this.isHovered = true
    },
    handleMouseOut () {
      this.isHovered = false
    }
  }
}
</script>

<style lang="stylus" scoped>
.background-container {
  position fixed
  left: 0;
  width: 100%;
  height: calc(100% - 50px);
  //background: url("../image/svg/back.svg") center/cover;
  background: url("../image/svg .png") center/cover
  //background-size: 100% 100%;
  overflow-y:scroll;
}
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.no-underline {
  text-decoration: none;
}

.no-underline:hover {
  text-decoration: none;
}
.el-tag {
  margin: 5px 0px 5px 0px ;
}
.el-link--inner {
   color: #1984dc;
}
.el-link:hover {
  color: #0ed5a6;
}

.medicine-card1 {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
  width: 40%;
  text-align: center;
  height: 79%;
  flex: none;
}
.textp p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
.autocomplete-border .elinput {
  border: none;
  box-shadow: none;
  border-radius: 0;
}
.autocomplete-border .el-autocomplete-suggestion {
}

@import "../../../assets/css/webpage.css";

.image-hover-effect {
  transition: transform 0.3s ease-out;
}
.image-hover-effect:hover {
  transform: scale(1.1);
}
.title_intrduction p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.medicine_title p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.content-page {
  padding-left 200px
  width: 700px;
  z-index 10px
  .item-container {
    margin-bottom 12px
  }
  .img {
    position fixed
  }
}
.content p {
  top -32px;
  padding-right: 70px;
  text-align: justify;
  word-wrap: break-word;
  overflow-wrap: break-word;
  margin-left: 3px;
  white-space: pre-line;
  font-size: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.title {
  margin-right: 470px;
}
.title h3 {
  //border-bottom: #5b5bef 2px solid;
  text-align: justify;
  color #5b5bef
  //margin-right 120px
  word-wrap: break-word;
  overflow-wrap: break-word;
  //display inline-block
}
.title h3:hover {
  color: #dc6666;
  //border-bottom: #dc6666 2px solid;
}
.selectype {
  position: absolute;
  white-space nowrap
  // align-items: center;
  margin: 20px 12px 3px 320px; /* 根据您的需求调整 */
  justify-content space-between
}
.liu-form-inline{
  // display flex
  justify-content space-between
}
</style>
